package com.zj.leetcode.medium;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: algorithm
 * @description: 无重复字符的最长子串
 * 3 longest-substring-without-repeating-characters
 * @author: Zhang Bo
 * @create: 2022-07-12 15:17:15
 **/
public class LongestSubstringWithoutRepeatingCharacters {
    public static void main(String[] args) {
//        String s = "abcabcbb";
//        String s = "pwwkew";
//        String s = "au";
//        String s = "abba";
        String s = "tmmzuxt";
        String[] ss = new String[]{"au", "pwwkew", "abcabcbb", "abba", "tmmzuxt"};
        Solution solution = new LongestSubstringWithoutRepeatingCharacters().new Solution();

        System.out.println(solution.lengthOfLongestSubstring(s));

        for (String a : ss) {
            System.out.println(solution.lengthOfLongestSubstring(a));
        }

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * s = "abcabcbb"
         *
         * @param s
         * @return
         */
        public int lengthOfLongestSubstring(String s) {
            if (s == null || s.length() <= 0) {
                return 0;
            }
            if(s.length() == 1){
                return 1;
            }

            Map<Character, Integer> map = new HashMap<>();

            int max = 0;

            int l = 0;
            int r = 0;
            int length = s.length();
            while (l < length && r < length) {
                if (map.containsKey(s.charAt(r))) {
                    map.remove(s.charAt(l));
                    max = Math.max(r - l, max);
                    l++;
                } else {
                    map.put(s.charAt(r), r);
                    r++;
                }

            }
            return Math.max(r - l, max);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
